package com.wennn.top.util;

import lombok.Data;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: wennn
 * @date: 6/2/20
 */
public class TreeBuilder {
    
    public static <T extends BTree> List<T> listToTree(List<T> inList){
        List<T> result = new ArrayList<>();
        for (T node : inList) {
            System.out.println(node);
            if("0".equals(node.getPId()+"")){
                result.add(findChild(node,inList));
            }
        }
        return result;
    }

    public static List<? extends BTree> treeToList(List<? extends BTree> inList){

        return null;
    }
 
    static <T extends BTree> T findChild(T node, List<T> list){
        for(T n:list){
            if(n.getPId() == node.getId()){
                if(node.getChildren() == null){
                    node.setChildren(new ArrayList<T>());
                }
                node.getChildren().add(findChild(n,list));
            }
        }
        return node;
    }

    @Data
    @ToString
    public static class BTree<T>{
        private T id;
        private T pId;
        private String name;
        List<? extends BTree> children;


        public BTree(){}

        public BTree(T id,String name,T pId){
            this.id = id;
            this.pId = pId;
            this.name = name;
        }


    }

    public static void main(String[] args) {
        BTree node1=new BTree(1,"山东省",0);
        BTree node2=new BTree(2,"德州市",1);
        BTree node3=new BTree(3,"夏津县",2);
        BTree node4=new BTree(4,"济南市",1);
        BTree node5=new BTree(5,"天津",0);
        BTree node6=new BTree(6,"红桥区",5);
        List<BTree> list=new ArrayList<>();
        list.add(node1);
        list.add(node2);
        list.add(node3);
        list.add(node4);
        list.add(node5);
        list.add(node6);
        listToTree(list).forEach(System.out::println);
 
    }
}
